package com.jrsoft.jrcore.http

import android.content.Context
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 所属系统:  杨梅红画院移动端
 * 所属模块:  网络请求模块
 * 功能描述: 构建网络请求的类
 * 创建时间: 2020/5/18 11:43
 * 维护人:  杨广
 * Copyright @ Jerrisoft 2019. All rights reserved.
 *┌──────────────────────────────────────────────────────────────┐
 *│ 此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．   │
 *│ 版权所有：杰人软件(深圳)有限公司                                │
 *└──────────────────────────────────────────────────────────────┘
 */
class RetrofitManager private constructor(host: String, private val timeout: Long) {
    private val mRetrofit: Retrofit

    init {
        mRetrofit = Retrofit.Builder().baseUrl(host)
            .client(getOkHttpClient(host))
            .addConverterFactory(NullOnEmptyConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


    /**  @des { 获取okhttp实列 }
     * @author 杨广
     * @date 2020/05/18 15:05
     * @param host String : host地址
     */
    private fun getOkHttpClient(host: String): OkHttpClient {
        return sOkHttpClient[host] ?: let {
            val builder = OkHttpClient.Builder()
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .cache(Cache(appContext.cacheDir, 10 * 1024 * 1024L))
            interceptorList.forEach { builder.addInterceptor(it) }
            builder.build().apply { sOkHttpClient[host] = this }
        }
    }

    companion object {
        private val sRetrofitManager = mutableMapOf<String, Retrofit>()
        private val sOkHttpClient = mutableMapOf<String, OkHttpClient>()
        lateinit var appContext: Context
        val interceptorList = mutableListOf<Interceptor>()


        /**
         * @des { 获取retrofit实例 }
         * @author 杨广
         * @date 2020/05/18 15:05
         * @param host String : host地址
         * @param timeout Long=30L : 超时时间.默认是30秒
         */
        fun <Service> getInstance(host: String, service: Class<Service>, timeout: Long = 30L): Service =
            sRetrofitManager[host]?.create(service) ?: run {
                val retrofit = RetrofitManager(host, timeout).mRetrofit
                sRetrofitManager[host] = retrofit
                return retrofit.create(service)
            }
    }
}